<?php

namespace Cktadmin\Controller;

use Common\Controller\BasicAdmin;
use Common\Service\DataService;

class CashController extends BasicAdmin {

    public $table = 'transaction';

    public function index() {
        $this->title = '提现记录';
        $where = array('type' => 2);
        $get = I('get.');
        (isset($get['key']) && $get['key'] !== '') && $where['user_name|order_no|alipay_account'] = array('like', "%{$get['key']}%");
        $count = M($this->table)->where($where)->count();
        $db = M($this->table)->where($where)->order('add_time desc');
        return parent::_list($db, $count);
    }

    function confirmCash() {
        $id = I('get.id', 0, 'intval');
        $info = M('transaction')->find($id);
        $user_info = M('user')->find($info['user_id']);
        $return = array('info' => '提交失败！', 'status' => 0);
        M()->startTrans(); //开启事务
        try {
            $data1 = array(
                'status' => 1,
                'processing_time' => time()
            );
            $result1 = M('transaction')->where(array('id' => $id))->save($data1);
            if ($result1 === false) {
                E('订单状态修改失败！');
            }
            $amount = $user_info['amount'] - $info['transaction_amount'];
            $data2 = array('amount' => $amount);
            $result2 = M('user')->where(array('id' => $user_info['id']))->save($data2);
            if ($result2 === false) {
                E('用户余额修改失败！');
            }
            M()->commit(); //提交事务
            $return['status'] = 1;
            $return['info'] = '操作成功！';
        } catch (\Exception $e) {
            M()->rollback(); //回滚
            $return['status'] = 0;
            $return['info'] = $e->getMessage();
        }
        $this->ajaxReturn($return);
    }

    public function del() {
        if (DataService::update($this->table)) {
            $this->success('删除成功！');
        }
        $this->error('删除失败！');
    }

}
